package com.atguigu.controller;


import com.atguigu.entity.HouseImage;
import com.atguigu.result.Result;
import com.atguigu.service.HouseImageService;
import com.atguigu.util.QiniuUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/houseImage")
public class HouseImageController {
    @DubboReference
    private HouseImageService houseImageService;

//    渲染文件上传视图
    @RequestMapping("/uploadShow/{houseId}/{type}")
    public String show(@PathVariable("houseId") Long houseId,
                       @PathVariable("type") Integer type,
                       ModelMap map) {
        map.addAttribute("houseId", houseId);
        map.addAttribute("type", type);
        return "house/upload";
    }

    //    接收文件并保存文件处理器
    @RequestMapping("/upload/{houseId}/{type}")
    @ResponseBody
    public Result upload(@PathVariable("houseId") Long houseId,
                         @PathVariable("type") Integer type,
                         @RequestParam("file") MultipartFile [] multipartFiles) throws IOException {

//        迭代MultipartFiles
        for (int i = 0; i < multipartFiles.length; i++) {

            MultipartFile multipartFile =  multipartFiles[i];
//            生成文件名
            String filename = UUID.randomUUID().toString();
            //            存储图片到七牛云
            QiniuUtil.upload2Qiniu(multipartFile.getBytes(),filename);
//            存储HouseImage到数据库
            HouseImage houseImage = new HouseImage();
//            创建图片的url
            String imageUrl = "http://rkfuv6xbx.hn-bkt.clouddn.com/" + filename;
            houseImage.setHouseId(houseId);
            houseImage.setImageName(filename);
            houseImage.setType(type);
            houseImage.setImageUrl(imageUrl);
            houseImageService.insert(houseImage);
        }
        return Result.ok();
    }
}
